package love.xin.view

import android.content.Context
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.RecyclerView

class CenteredGridLayoutManager(
    context: Context,
    spanCount: Int
) : GridLayoutManager(context, spanCount) {

    override fun onLayoutChildren(recycler: RecyclerView.Recycler, state: RecyclerView.State) {
        super.onLayoutChildren(recycler, state)

        // 获取 RecyclerView 宽度
        val totalWidth = width
        // 遍历每行的视图
        for (i in 0 until childCount step spanCount) {
            var rowWidth = 0
            for (j in 0 until spanCount) {
                val view = getChildAt(i + j) ?: break
                measureChildWithMargins(view, 0, 0)
                rowWidth += getDecoratedMeasuredWidth(view)
            }

            // 计算每行居中的偏移量
            val offset = (totalWidth - rowWidth) / 2
            for (j in 0 until spanCount) {
                val view = getChildAt(i + j) ?: break
                layoutDecoratedWithMargins(
                    view,
                    getDecoratedLeft(view) + offset,
                    getDecoratedTop(view),
                    getDecoratedRight(view) + offset,
                    getDecoratedBottom(view)
                )
            }
        }
    }
}
